﻿#include "dlgsystemset.h"
#include "ui_dlgsystemset.h"
#include "globalsymbol.h"

#include "sdk/QsLog/include/QsLog.h"

#include <QDebug>
#include <QRegExpValidator>
#include <QDateTime>
#include <QDir>
#include <QFile>
#include <QCollator>
#include <QMessageBox>

DlgSystemSet::DlgSystemSet(QSettings* settings, QWidget *parent) :
    QDialog(parent),
    ui(new Ui::DlgSystemSet),
    m_settings(settings),
    m_fromLevel(false)
{
    ui->setupUi(this);

    // 初始化
    initUI();
    init();
}

DlgSystemSet::~DlgSystemSet()
{
    delete ui;
}

void DlgSystemSet::initUI()
{
    setWindowFlags(Qt::CustomizeWindowHint | Qt::WindowTitleHint | Qt::MSWindowsFixedSizeDialogHint);

    // 测试项目
    m_bgItem = new QButtonGroup(this);
    m_bgItem->addButton(ui->rdoAssemble, 0);
    m_bgItem->addButton(ui->rdoUnit, 1);
    // 测试阶段
    m_bgStage = new QButtonGroup(this);
    m_bgStage->addButton(ui->rdoM, 0);
    m_bgStage->addButton(ui->rdoC, 1);
    m_bgStage->addButton(ui->rdoS, 2);
    m_bgStage->addButton(ui->rdoD, 3);

    // 设置浮点数的取值范围, 保留小数点后2位
    QRegExp reTempeture("^-?(100|1?[0-7]?\\d(\\.\\d{1,2})?)$");
    ui->leTempeture->setValidator(new QRegExpValidator(reTempeture, this));
    QRegExp reHumidity("^(([1-9][0-9]|[1-9])(\\.\\d{1,2})?|0\\.\\d{1,2}|100)$");
    ui->leHumidity->setValidator(new QRegExpValidator(reHumidity, this));

    connect(ui->btnOk,  &QPushButton::clicked, this, &DlgSystemSet::onOk);
    connect(ui->btnCancel, &QPushButton::clicked, this, &DlgSystemSet::onCancel);
}

void DlgSystemSet::init()
{
    m_settings->beginGroup("SystemSet");
    int item = m_settings->value("item").toInt();
    int stage = m_settings->value("stage").toInt();
    QString A1Num = m_settings->value("A1Num").toString();
    QString A2Num = m_settings->value("A2Num").toString();
    QString A3Num = m_settings->value("A3Num").toString();
    QString A4Num = m_settings->value("A4Num").toString();
    QString CtrlNum = m_settings->value("CtrlNum").toString();
    QString tempeture = m_settings->value("tempeture").toString();
    QString humidity = m_settings->value("humidity").toString();
    QString person = m_settings->value("person").toString();
    QString kdperv = m_settings->value("kdperv").toString();
    QString description = m_settings->value("description").toString();
    QStringList servoMachineList = m_settings->value("servoMachine").toStringList();
    m_settings->endGroup();

    // 测试项目
    switch (item) {
    case 0:
        ui->rdoAssemble->setChecked(true);
        break;
    case 1:
        ui->rdoUnit->setChecked(true);
        break;
    default:
        break;
    }

    // 测试阶段
    switch (stage) {
    case 0:
        ui->rdoM->setChecked(true);
        break;
    case 1:
        ui->rdoC->setChecked(true);
        break;
    case 2:
        ui->rdoS->setChecked(true);
        break;
    case 3:
        ui->rdoD->setChecked(true);
        break;
    default:
        break;
    }

    // 伺服机构编号, 控制器编号
    ui->leA1Num->setText(A1Num);
    ui->leA2Num->setText(A2Num);
    ui->leA3Num->setText(A3Num);
    ui->leA4Num->setText(A4Num);
    ui->leCtrlNum->setText(CtrlNum);

    // 温度, 湿度, 人员, Kdperv, 测试说明
    ui->leTempeture->setText(tempeture);
    ui->leHumidity->setText(humidity);
    ui->lePerson->setText(person);
    ui->leKdperv->setText(kdperv);
    ui->txtDescription->setText(description);

    // 伺服机构选择
    if (servoMachineList.contains("A1"))
        ui->chkA1->setChecked(true);
    if (servoMachineList.contains("A2"))
        ui->chkA2->setChecked(true);
    if (servoMachineList.contains("A3"))
        ui->chkA3->setChecked(true);
    if (servoMachineList.contains("A4"))
        ui->chkA4->setChecked(true);
}

void DlgSystemSet::deleteFilesBefore15days()
{
    // 比较日期
    QString before = QDate::currentDate().addDays(-STORAGE_DISK_DAYS).toString("yyyy-MM-dd");

    // 存盘路径
    m_settings->beginGroup("Storage");
    QString savePath = m_settings->value("savePath").toString();
    QString reportPath = m_settings->value("reportPath").toString();
    m_settings->endGroup();
    savePath = savePath.prepend(qApp->applicationDirPath());
    reportPath = reportPath.prepend(qApp->applicationDirPath());

    // 找到存储路径下的所有data文件
    QStringList deleteDataFileList;
    QDir dir(savePath);
    QStringList filter;
    filter << "*.dat";
    dir.setNameFilters(filter);
    QFileInfoList fileInfoList = dir.entryInfoList(filter);
    for (int i = 0; i < fileInfoList.size(); i++) {
        QString fileName = fileInfoList.at(i).fileName();
        if (fileName.startsWith("data")) {
            QString dateString = fileName.mid(5, 10);
            if ( (QString::compare(dateString, before) < 0) ) {
                deleteDataFileList << fileName;
            }
        }
    }

    // 删除规定天数之前的文件
    for (int i = 0; i < deleteDataFileList.size(); i++) {
        QString filename = QStringLiteral("%1/%2").arg(savePath, deleteDataFileList.at(i));
        if (!QFile::remove(filename)) {
            QLOG_ERROR() << "delete dat file error: " << filename;
        }
    }

    // 找到存储路径下的所有report文件
    QStringList deleteReportFileList;
    dir.setPath(reportPath);
    filter.clear();
    filter << "*.csv";
    dir.setNameFilters(filter);
    fileInfoList = dir.entryInfoList(filter);
    for (int i = 0; i < fileInfoList.size(); i++) {
        QString fileName = fileInfoList.at(i).fileName();
        if (fileName.startsWith("report")) {
            QString dateString = fileName.mid(7, 10);
            if ( (QString::compare(dateString, before) < 0) ) {
                deleteReportFileList << fileName;
            }
        }
    }

    // 删除规定天数之前的文件
    for (int i = 0; i < deleteReportFileList.size(); i++) {
        QString filename = QStringLiteral("%1/%2").arg(reportPath, deleteReportFileList.at(i));
        if (!QFile::remove(filename)) {
            QLOG_ERROR() << "delete report file error: " << filename;
        }
    }
}

void DlgSystemSet::onOk()
{
    if (ui->leA1Num->text().isEmpty()) {
        QMessageBox::information(this, QStringLiteral("提示"), QStringLiteral("A1伺服机构编号为空!"));
        return;
    }
    if (ui->leA2Num->text().isEmpty()) {
        QMessageBox::information(this, QStringLiteral("提示"), QStringLiteral("A2伺服机构编号为空!"));
        return;
    }
    if (ui->leA3Num->text().isEmpty()) {
        QMessageBox::information(this, QStringLiteral("提示"), QStringLiteral("A3伺服机构编号为空!"));
        return;
    }
    if (ui->leA4Num->text().isEmpty()) {
        QMessageBox::information(this, QStringLiteral("提示"), QStringLiteral("A4伺服机构编号为空!"));
        return;
    }
    if (ui->leCtrlNum->text().isEmpty()) {
        QMessageBox::information(this, QStringLiteral("提示"), QStringLiteral("控制器编号为空!"));
        return;
    }
    if (ui->leTempeture->text().isEmpty()) {
        QMessageBox::information(this, QStringLiteral("提示"), QStringLiteral("温度为空!"));
        return;
    }
    if (ui->leHumidity->text().isEmpty()) {
        QMessageBox::information(this, QStringLiteral("提示"), QStringLiteral("湿度为空!"));
        return;
    }
    if (ui->lePerson->text().isEmpty()) {
        QMessageBox::information(this, QStringLiteral("提示"), QStringLiteral("测试人员为空!"));
        return;
    }
    if (ui->leKdperv->text().isEmpty()) {
        QMessageBox::information(this, QStringLiteral("提示"), QStringLiteral("Kdperv为空!"));
        return;
    }
    if (ui->txtDescription->toPlainText().isEmpty()) {
        QMessageBox::information(this, QStringLiteral("提示"), QStringLiteral("测试说明为空!"));
        return;
    }

    QStringList servoMachineList;
    if (ui->chkA1->isChecked())
        servoMachineList << "A1";
    if (ui->chkA2->isChecked())
        servoMachineList << "A2";
    if (ui->chkA3->isChecked())
        servoMachineList << "A3";
    if (ui->chkA4->isChecked())
        servoMachineList << "A4";

    m_settings->beginGroup("SystemSet");
    m_settings->setValue("item", m_bgItem->checkedId());
    m_settings->setValue("stage", m_bgStage->checkedId());
    m_settings->setValue("A1Num", ui->leA1Num->text());
    m_settings->setValue("A2Num", ui->leA2Num->text());
    m_settings->setValue("A3Num", ui->leA3Num->text());
    m_settings->setValue("A4Num", ui->leA4Num->text());
    m_settings->setValue("CtrlNum", ui->leCtrlNum->text());
    m_settings->setValue("tempeture", ui->leTempeture->text());
    m_settings->setValue("humidity", ui->leHumidity->text());
    m_settings->setValue("person", ui->lePerson->text());
    m_settings->setValue("kdperv", ui->leKdperv->text());
    m_settings->setValue("description", ui->txtDescription->toPlainText());
    m_settings->setValue("servoMachine", servoMachineList);
    m_settings->endGroup();

    // 从级别选择对话框进入完成
    m_fromLevel = false;

    // 删除15天以前的数据文件(包括报表文件)
    deleteFilesBefore15days();

    //QMessageBox::information(this, QStringLiteral("提示"), QStringLiteral("保存成功!"));

    this->accept();
}

void DlgSystemSet::onCancel()
{
    if (m_fromLevel) {
        QMessageBox::information(this, QStringLiteral("提示"), QStringLiteral("请点击确定进入主界面后再取消操作!"));
    } else {
        this->reject();
    }
}

void DlgSystemSet::onShow()
{
    // 从级别选择对话框进入的
    m_fromLevel = true;

    this->show();
}
